﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web.Mvc;
using Beeldbankmvc.Code;
using Beeldbankmvc.Models;
using System.Web.UI;

namespace Beeldbankmvc.Controllers
{
    public class GebiedController : Controller
    {
        BeeldbankLinqDataContext beeldBankDB = new BeeldbankLinqDataContext();
        GebiedRepository gebiedRepository = new GebiedRepository();

        public ActionResult Index(int? gebiedId = 1)
        {
            // Nu nederland kaart als ID 1 en default waarde
            var gebied = beeldBankDB.BEELDBANK_GEBIEDs.Where(p => p.Id == gebiedId.Value).SingleOrDefault();

            Double topLeftLat = gebied.linksBovenLatitude.Value;
            Double topLeftLon = gebied.linksBovenLongitude.Value;
            Double topRightLat = gebied.rechtsOnderLatitude.Value;
            Double topRightLon = gebied.rechtsOnderLongitude.Value;

            String imageFullPath = Server.MapPath("~/Content/Images/maps/") + gebied.Plaatje;
            AreaModel locsModel = Gebied.renderImageMapForMapIndex(topLeftLat, topLeftLon, topRightLat, topRightLon, imageFullPath);

            return View(locsModel);
        }

        public ActionResult MapIndex(int Id)
        {
            return RedirectToAction("Index", "Gebied", new { gebiedId = Id });
        }

        //
        // /Gebied/Select
        public ActionResult Select(int? id)
        {
            TempData["mapId"] = id;
            
            return RedirectToAction("Map", "Gebied", new {mapId = id });
        }

        public ActionResult SelectYear(int id, string year)
        {
            string fromDate = "1-1-" + year.ToString();
            string toDate ="31-12-" + year.ToString();

            return RedirectToAction("Map", "Gebied", new {mapId = id, fromDate = fromDate, toDate = toDate });
        }

        // cache the search query for a day
        [OutputCache(Duration = (3600 * 24), VaryByParam = "*", VaryByCustom = "IsLoggedIn", Location = OutputCacheLocation.Server)]
        public ActionResult Map(string fromDate, string toDate, int mapId)
        {
            TempData["mapId"] = mapId;

            var gebied = beeldBankDB.BEELDBANK_GEBIEDs.Where(p => p.Id == mapId).SingleOrDefault();

            Double topLeftLat = gebied.linksBovenLatitude.Value;
            Double topLeftLon = gebied.linksBovenLongitude.Value;
            Double topRightLat = gebied.rechtsOnderLatitude.Value;
            Double topRightLon = gebied.rechtsOnderLongitude.Value;

            String imageFullPath = Server.MapPath("~/Content/Images/maps/") + gebied.Plaatje;
            String areaName = gebied.Naam;
            LocationsModel locsModel = Gebied.renderImageMapForMap(topLeftLat, topLeftLon, topRightLat, topRightLon, imageFullPath, areaName, fromDate, toDate, false, mapId);

            // save all ID's of this search page to be able to navigate trough the results in detail mode
            #region In memory results index
            TempData["resultIdList"] = null;
            TempData["resultArea"] = topLeftLat + "|" + topLeftLon + "|" + topRightLat + "|" + topRightLon + "|" + fromDate;
            TempData["resultIdType"] = "Map";
            #endregion

            return View(locsModel);
        }

        //post
        [HttpPost]
        public ActionResult Map(FormCollection collection)
        {
            // Store the selected region form MAP button
            int mapId = 0;
            if (TempData["mapId"] != null)
            {
                mapId = (int)TempData["mapId"];
                TempData["mapId"] = mapId;
            }
            else
            {
                if (mapId == 0)
                {
                    mapId = Convert.ToInt32(Request.Form["mapId"]);
                    TempData["mapId"] = mapId;
                }
            }

            if(!String.IsNullOrEmpty(collection["fromDate"]))
            {
                DateTime toDate = Convert.ToDateTime(collection["fromDate"]).AddYears(1);
                return RedirectToAction("MapForPost", "Gebied", new { topLeftLat = collection["topLeftLat"], topLeftLon = collection["topLeftLon"], topRightLat = collection["topRightLat"], topRightLon = collection["topRightLon"], imageName = collection["imageName"], fromDate = collection["fromDate"], toDate, mapId = mapId });
            }
            return RedirectToAction("MapForPost", "Gebied", new { topLeftLat = collection["topLeftLat"], topLeftLon = collection["topLeftLon"], topRightLat = collection["topRightLat"], topRightLon = collection["topRightLon"], imageName = collection["imageName"], mapId = mapId });
        }

        public ActionResult MapForPost(string topLeftLat, string topLeftLon, string topRightLat, string topRightLon, string imageName, string areaName, string fromDate, string toDate, int mapId)
        {
            TempData["mapId"] = mapId;

            double topLeftLatitude = 0;
            double topLeftLongitude = 0;
            double topRightLatitude = 0;
            double topRightLongitude = 0;

            if (topLeftLat != null)
                topLeftLatitude = Convert.ToDouble(topLeftLat.Replace(".", ","));

            if (topLeftLon != null)
                topLeftLongitude = Convert.ToDouble(topLeftLon.Replace(".", ","));

            if (topRightLat != null)
                topRightLatitude = Convert.ToDouble(topRightLat.Replace(".", ","));

            if (topRightLon != null)
                topRightLongitude = Convert.ToDouble(topRightLon.Replace(".", ","));

            String imageFullPath = Server.MapPath("~/Content/Images/maps/") + imageName;
            LocationsModel locsModel = Gebied.renderImageMapForMap(topLeftLatitude, topLeftLongitude, topRightLatitude, topRightLongitude, imageFullPath, areaName, fromDate, toDate, false, mapId);

            // save all ID's of this search page to be able to navigate trough the results in detail mode
            #region In memory results index
            TempData["resultIdList"] = null; // resultIdList.TrimEnd(',');

            TempData["resultArea"] = topLeftLat + "|" + topLeftLon + "|" + topRightLat + "|" + topRightLon + "|" + fromDate;
            TempData["resultIdType"] = "Map";
            #endregion

            return View(locsModel);
        }

        [HttpPost]
        [Authorize(Roles = "Administrator, Beheerder")]
        public ActionResult Edit(FormCollection collection)
        {
            if (collection["submit"].Equals("Opslaan"))
            {
                var gebied = from o in beeldBankDB.BEELDBANK_GEBIEDs
                             where o.Plaatje.Equals(collection["imageName"])
                             select o;

                if (gebied == null)
                {
                    BEELDBANK_GEBIED nieuwGebied = new BEELDBANK_GEBIED();
                    nieuwGebied.linksBovenLatitude = Convert.ToDouble(collection["topLeftLat"]);
                    nieuwGebied.linksBovenLongitude = Convert.ToDouble(collection["topLeftLon"]);
                    nieuwGebied.rechtsOnderLatitude = Convert.ToDouble(collection["topRightLat"]);
                    nieuwGebied.rechtsOnderLongitude = Convert.ToDouble(collection["topRightLon"]);
                    nieuwGebied.Plaatje = collection["imageName"];
                    nieuwGebied.Naam = collection["areaName"];
                    beeldBankDB.BEELDBANK_GEBIEDs.InsertOnSubmit(nieuwGebied);
                    beeldBankDB.SubmitChanges();
                }
                else
                {
                    var bestaandGebied = gebied.FirstOrDefault();

                    bestaandGebied.linksBovenLatitude = Convert.ToDouble(collection["topLeftLat"]);
                    bestaandGebied.linksBovenLongitude = Convert.ToDouble(collection["topLeftLon"]);
                    bestaandGebied.rechtsOnderLatitude = Convert.ToDouble(collection["topRightLat"]);
                    bestaandGebied.rechtsOnderLongitude = Convert.ToDouble(collection["topRightLon"]);
                    bestaandGebied.Plaatje = collection["imageName"];
                    bestaandGebied.Naam = collection["areaName"];
                    beeldBankDB.SubmitChanges();
                }
            }

            return RedirectToAction("Edit", "Gebied", new { topLeftLat = collection["topLeftLat"], topLeftLon = collection["topLeftLon"], topRightLat = collection["topRightLat"], topRightLon = collection["topRightLon"], imageName = collection["imageName"], areaName = collection["areaName"] });
        }

        [Authorize(Roles = "Administrator, Beheerder")]
        public ActionResult Edit(string topLeftLat, string topLeftLon, string topRightLat, string topRightLon, string imageName, string areaName, string fromDate, string toDate)
        {
            double topLeftLatitude = 0;
            double topLeftLongitude = 0;
            double topRightLatitude = 0;
            double topRightLongitude = 0;

            if (topLeftLat != null)
                topLeftLatitude = Convert.ToDouble(topLeftLat.Replace(".",","));

            if (topLeftLon != null)
                topLeftLongitude = Convert.ToDouble(topLeftLon.Replace(".", ","));

            if (topRightLat != null)
                topRightLatitude = Convert.ToDouble(topRightLat.Replace(".", ","));

            if (topRightLon != null)
                topRightLongitude = Convert.ToDouble(topRightLon.Replace(".", ","));

            String imageFullPath = Server.MapPath("~/Content/Images/maps/") + imageName; //Server.MapPath("~/Content/Images/maps/") +
            LocationsModel locsModel = Gebied.renderImageMapForMap(topLeftLatitude, topLeftLongitude, topRightLatitude, topRightLongitude, imageFullPath, areaName, fromDate, toDate, true, -1);

            return View(locsModel);
        }

        [Authorize(Roles = "Administrator, Beheerder")]
        public ActionResult GenerateSQLViewCode()
        {
            GebiedRepository gebiedRepository = new GebiedRepository();

            return View(gebiedRepository.FindAll());
        }
       
        [Authorize(Roles = "Administrator, Beheerder")]
        public ActionResult Create()
        {
            return View();
        }
        
        [HttpPost]
        [Authorize(Roles = "Administrator, Beheerder")]
        public ActionResult Create(FormCollection collection)
        {
            if (collection["submit"].Equals("Opslaan"))
            {
                var gebied = from o in beeldBankDB.BEELDBANK_GEBIEDs
                             where o.Plaatje.Equals(collection["imageName"])
                             select o;

                if (gebied.Count() == 0)
                {
                    BEELDBANK_GEBIED nieuwGebied = new BEELDBANK_GEBIED();
                    nieuwGebied.linksBovenLatitude = Convert.ToDouble(collection["topLeftLat"]);
                    nieuwGebied.linksBovenLongitude = Convert.ToDouble(collection["topLeftLon"]);
                    nieuwGebied.rechtsOnderLatitude = Convert.ToDouble(collection["topRightLat"]);
                    nieuwGebied.rechtsOnderLongitude = Convert.ToDouble(collection["topRightLon"]);
                    nieuwGebied.Plaatje = collection["imageName"];
                    nieuwGebied.Naam = collection["areaName"];
                    beeldBankDB.BEELDBANK_GEBIEDs.InsertOnSubmit(nieuwGebied);
                    beeldBankDB.SubmitChanges();
                    return RedirectToAction("Edit", "Gebied", new { topLeftLat = collection["topLeftLat"], topLeftLon = collection["topLeftLon"], topRightLat = collection["topRightLat"], topRightLon = collection["topRightLon"], imageName = collection["imageName"], areaName = collection["areaName"] });
                }
                else
                {
                    ViewBag.ImageInUse = collection["imageName"] + " is in gebruik";
                }
            }

            return View();
        }

        public ActionResult DisplayDotsOnMap(double? topLeftLat, double? topLeftLon, double? topRightLat, double? topRightLon, string imageName, string fromDate, string toDate, bool isEdit, int mapId)
        {
            string imageFullPath = Server.MapPath("~/Content/Images/maps/") + imageName;
            Image mapImage = Gebied.drawDotsOnMap(topLeftLat, topLeftLon, topRightLat, topRightLon, imageFullPath, fromDate, toDate, isEdit, mapId);
            return new ImageResult { Image = mapImage, ImageFormat = ImageFormat.Jpeg };
        }

        public ActionResult DisplayAreasOnMapIndex(double? topLeftLat, double? topLeftLon, double? topRightLat, double? topRightLon, string imageFullPath)
        {
            Image mapImage = Gebied.drawAreasOnMapIndex(topLeftLat, topLeftLon, topRightLat, topRightLon, imageFullPath);
            return new ImageResult { Image = mapImage, ImageFormat = ImageFormat.Jpeg };
        }

        public ActionResult DisplayOneDotOnMap(int mapId, int mediaObjectId)
        {
            BEELDBANK_GEBIED beeldbankGebied = gebiedRepository.FindOne(mapId);
            if (beeldbankGebied != null)
            {
                string imageFullPath = Server.MapPath("~/Content/Images/maps/") + beeldbankGebied.Plaatje;
                Image mapImage = Gebied.drawOneDotOnMap(beeldbankGebied.linksBovenLatitude, beeldbankGebied.linksBovenLongitude, beeldbankGebied.rechtsOnderLatitude, beeldbankGebied.rechtsOnderLongitude, imageFullPath, mapId, mediaObjectId);
                return new ImageResult { Image = mapImage, ImageFormat = ImageFormat.Jpeg };
            }
            else
                return null;
        }
    }
}
